<template>
  <div class="shopCard">
    <p class="title">购物车</p>
    <el-scrollbar v-if="shopCards.length !== 0" max-height="550px">
      <GoodsCardItem
        v-for="good in goodsInfo"
        :good="good"
        :key="good.id"
        @changeChoose="changeChoose"
        @changeNum="changeNum"></GoodsCardItem>
    </el-scrollbar>
    <el-empty
      v-if="shopCards.length == 0"
      style="height: 550px"
      description="您的购物车还没有商品" />
    <div class="charge-shop-cart">
      <el-statistic title="总价" :value="totalPriceAll" />
      <el-button type="success" plain @click="goToPay">支付</el-button>
    </div>
  </div>
</template>

<script setup>
import { getGoodsInfo } from '@/api/goods'
import { getShopCardInfo } from '@/api/personInfo'
import GoodsCardItem from '@/components/GoodsCardItem.vue'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

const userStore = useUserStore()

const user = userStore.getUserInfo()

// 购物车记录
const shopCards = ref([])

// 所有商品的信息
const goodsInfo = ref([])

const getAllShopCard = async () => {
  const res = (await getShopCardInfo(user.id)).data
  if (res.code == 505) {
    ElMessage.error(res.msg)
    return
  }
  shopCards.value = res.data
  // 获取所有商品的信息
  for (let i of shopCards.value) {
    const res = (await getGoodsInfo(i.goodsId)).data
    goodsInfo.value.push({ ...res.data, shopId: i.id, isChoose: i.isChoose, num: i.num })
  }
}

getAllShopCard()

// 改变选中
const changeChoose = (obj) => {
  const res = goodsInfo.value.find((item) => item.shopId == obj.shopId)
  res.isChoose = obj.isChoose
}

// 改变数量
const changeNum = (obj) => {
  const res = goodsInfo.value.find((item) => item.shopId == obj.shopId)
  res.num = obj.num
}

// 选中商品总价
const totalPriceAll = computed(() => {
  return goodsInfo.value.reduce(
    (sum, item) => (item.isChoose ? sum + item.price * item.num : sum),
    0
  )
})

// 跳转支付页
const goToPay = () => {
  const payItems = goodsInfo.value.filter((item) => item.isChoose)
  sessionStorage.setItem('payItem', JSON.stringify(payItems))
  router.push('/pay')
}
</script>

<style scoped>
.shopCard {
  flex-direction: column;
  width: 1550px;
  height: 600px;
  background-color: white;
  margin: 100px auto;
  margin-top: 0px;
}

.title {
  margin: 0px 0 0 20px;
  font-size: 28px;
  font-weight: 500;
}

.el-scrollbar {
  padding-left: 60px;
}

.charge-shop-cart {
  position: relative;
  top: -7%;
  display: flex;
  align-items: center;
  background-color: #e5eaf3;
  height: 60px;
}

.charge-shop-cart .el-button {
  width: 100px;
  margin-left: 20px;
}

.el-statistic {
  margin-left: 1000px;
}
</style>
